<template>
  <div>
    <el-form label-width="100px" :model="skuForm">
      <el-form-item label="SPU名称"> {{ spu.spuName }} </el-form-item>

      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)">
        <el-input
          placeholder="价格(元)"
          type="number"
          v-model="skuForm.price"
        ></el-input>
      </el-form-item>

      <el-form-item label="重量(千克)">
        <el-input
          placeholder="重量(千克)"
          type="number"
          v-model="skuForm.weight"
        ></el-input>
      </el-form-item>

      <el-form-item label="规格描述">
        <el-input
          placeholder="规格描述"
          type="textarea"
          rows="4"
          v-model="skuForm.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="attr.attrName"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <el-select v-model="attr.attrIdValueId" placeholder="请选择">
              <el-option
                v-for="(attrValue, index) in attr.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
                :value="`${attr.id}:${attrValue.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-form :inline="true" label-width="100px">
          <el-form-item
            :label="spuSaleAttr.saleAttrName"
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
          >
            <el-select
              v-model="spuSaleAttr.spuSaleAttrIdValueId"
              placeholder="请选择"
            >
              <el-option
                v-for="(
                  spuSaleAttrValue, index
                ) in spuSaleAttr.spuSaleAttrValueList"
                :key="spuSaleAttrValue.id"
                :label="spuSaleAttrValue.saleAttrValueName"
                :value="`${spuSaleAttr.id}:${spuSaleAttrValue.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>

      <el-form-item label="图片列表">
        <el-table
          border
          style="width: 100%"
          :data="spuImageList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="prop" label="图片" width="width">
            <template slot-scope="{ row, $index }">
              <img
                :src="row.imgUrl"
                alt=""
                style="width: 100px; height: 80px"
              />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button v-if="row.isDefault === '0'" type="primary" size="mini" @click="changeDefault(row,spuImageList)">设为默认</el-button>
              <el-tag v-else type="success">默认</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SkuForm",
  // props:['visible']
  data() {
    return {
      spu: {},
      attrList: [],  
      spuSaleAttrList: [],
      spuImageList: [],  //这个数组是spu的所有的图片列表
      skuImageList:[],
      skuForm: {
        // 父组件给传递的
        spuId: "",
        category3Id: "",
        tmId: "",

        // v-model直接收集
        price: "",
        skuName: "",
        skuDesc: "",
        weight: "",
        // createTime: "2021-05-06T02:12:14.318Z",
        // id: 0,
        // isSale: 0,

        // 通过自己写代码收集
        skuDefaultImg: "",

        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: "string",
          //   id: 0,
          //   skuId: 0,
          //   valueId: 0,
          //   valueName: "string",
          // },
        ],

        skuImageList: [
          // {
          //   id: 0,
          //   imgName: "string",
          //   imgUrl: "string",
          //   isDefault: "string",
          //   skuId: 0,
          //   spuImgId: 0,
          // },
        ],

        skuSaleAttrValueList: [
          // {
          //   id: 0,
          //   saleAttrId: 0,
          //   saleAttrName: "string",
          //   saleAttrValueId: 0,
          //   saleAttrValueName: "string",
          //   skuId: 0,
          //   spuId: 0,
          // },
        ],
      },
    };
  },

  methods: {
    async getInitAddSkuFormData(row, category1Id, category2Id) {
      this.spu = row;
      // 获取平台属性列表
      // http://localhost:9529/dev-api/admin/product/attrInfoList/2/13/61
      let promise1 = this.$API.attr.getList(
        category1Id,
        category2Id,
        row.category3Id
      );
      // 获取spu的销售属性列表
      // http://localhost:9529/dev-api/admin/product/spuSaleAttrList/4
      let promise2 = this.$API.sku.getSpuSaleAttrList(row.id);
      // 获取spu的图片列表  （因为sku的图片列表是从spu的图片列表当中选择而来的）
      // http://localhost:9529/dev-api/admin/product/spuImageList/4
      let promise3 = this.$API.sku.getSpuImageList(row.id);
      // Promise.all  是个方法
      // 功能： 并发处理多个promise
      // 参数： 数组  promise对象的数组
      // 返回值： promise对象
      // 成功（数组中所有的promise对象都成功） 所有的promise成功的结果组成的数组
      // 失败（数组中只要有一个promise对象失败就失败） 第一个失败的promise失败的原因

      const result = await Promise.all([promise1, promise2, promise3]);
      this.attrList = result[0].data;
      this.spuSaleAttrList = result[1].data;
      let spuImageList = result[2].data
      spuImageList.forEach(item => item.isDefault = '0')
      this.spuImageList = spuImageList;
    },
    //表格选中状态发生改变的回调
    handleSelectionChange(val){
      this.skuImageList = val
    },
    //点击设为默认按钮（排它）
    changeDefault(row,spuImageList){
      spuImageList.forEach(item => item.isDefault = '0')
      row.isDefault = '1'
      this.skuForm.skuDefaultImg = row.imgUrl  //收集默认图片的路径
    },
    //清空data所有的数据
    resetData(){
      // 功能：把第二个参数对象当中的东西拷贝到第一个对象当中
      // 参数：俩对象
      // 返回值：返回的是目标对象
      // assign 方法完成的相当于是浅拷贝
      // this.$options.data()初始化的data对象,刚开始的data对象和this._data不是同一个对象
      // this._data是当前操作的data对象
      // {a:100,arr:[1,2,3]}  {a:100，arr:[1,2,3]}
      Object.assign(this._data,this.$options.data())
    },
    //点击保存
    async save(){
      //获取参数数据
      let {spu,attrList,spuSaleAttrList,skuImageList,skuForm} = this
      //整理参数
      skuForm.spuId = spu.id
      skuForm.category3Id = spu.category3Id
      skuForm.tmId = spu.tmId
      
      //最终需要的图片格式
       // {
      //   imgName: "string",
      //   imgUrl: "string",
      //   isDefault: "string",
      //   spuImgId: 0,
      // },
      //目前我们的
      // id:22
      // imgName:"9316593be50948f8.jpg"
      // imgUrl:"http://47.93.148.192:8080/group1/M00/00/02/rBHu8l-sklaALrngAAHGDqdpFtU741.jpg"
      // isDefault:"0"
      // spuId:4
      skuForm.skuImageList = skuImageList.map(item => {
        return {
          imgName:item.imgName,
          imgUrl:item.imgUrl,
          isDefault:item.isDefault,
          spuImgId:item.id
        }
      })

      //整理平台属性值列表和销售属性值列表
      skuForm.skuAttrValueList = attrList.reduce((prev,item) => {  
        if(item.attrIdValueId){
          let [attrId,valueId] = item.attrIdValueId.split(':')
          let obj = {attrId,valueId}
          prev.push(obj)
        }
        return prev
      },[])

      skuForm.skuSaleAttrValueList = spuSaleAttrList.reduce((prev,item) => {
        if(item.spuSaleAttrIdValueId){
          let [saleAttrId,saleAttrValueId] = item.spuSaleAttrIdValueId.split(':')
          let obj = {saleAttrId,saleAttrValueId}
          prev.push(obj)
        }
        return prev
      },[])
      //发请求
      try {
        //成功
        const result = await this.$API.sku.addUpdate(skuForm)
        if(result.code === 200 || result.code === 20000){
          this.$message.success('保存sku成功')
          // 回到列表页
          this.$emit('update:visible',false)
          // console.log(this.$options.data())
          // console.log(this._data)
          this.resetData()
          //不需要父组件重新发请求
          //只需要把data数据清空
        }else{
          this.$message.error('保存sku失败')
        }
        
      } catch (error) {
         //失败
        this.$message.error('请求保存sku失败')
      }
    },
    //取消操作
    cancel(){
      this.$emit('update:visible',false)
      this.resetData()
    }
  },
};
</script>

